package shiro.com.utils.shiro.realm;



import io.jsonwebtoken.Claims;
import jdk.nashorn.internal.runtime.ErrorManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.juli.logging.Log;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import shiro.com.domain.sys.SysRoleTest;
import shiro.com.domain.sys.SysUsers;
import shiro.com.service.sys.ISysRoleTestService;
import shiro.com.service.sys.ISysUsersService;
import shiro.com.service.sys.ISysResoureTestService;
import shiro.com.utils.shiro.token.JwtToken;
import shiro.com.utils.shiro.util.JwtUtil;

import java.util.Set;


/**
 * Created by yangqj on 2017/4/21.
 */
@Component
@Slf4j
public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    ISysUsersService sysUsersService;
    @Autowired
    private ISysRoleTestService sysRoleTestService;
    @Autowired
    private ISysResoureTestService sysResoureTestService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userName = (String)principalCollection.iterator().next();
        Set<String> sysRoleTest = sysRoleTestService.selectSysRoleTestByUserName(userName);
        Set<String> sysResoureTest = sysResoureTestService.selectSysResoureTestByUserName(userName);


        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(sysRoleTest);
        simpleAuthorizationInfo.setStringPermissions(sysResoureTest);

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
      //UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        JwtToken jwtToken = (JwtToken)authenticationToken;
     //获取名字
        String jwt = (String)jwtToken.getPrincipal();
        Claims claims = JwtUtil.parseJWT(jwt);
        String username = claims.getId();
        SysUsers users = sysUsersService.selectByUsername(username);
        if (users == null){
            return  null;
        }
        //进行简单的身份验证
        return new SimpleAuthenticationInfo(username,users.getSysUserPsw(),getName());
    }
}
